package com.googlecode.cswish.struts.interceptor;

import java.util.Map;

import javax.annotation.Resource;

import com.googlecode.cswish.model.PageElements;
import com.googlecode.cswish.struts.conversion.AutoPageConverterManager;
import com.googlecode.cswish.util.FrameConstant;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.config.entities.ActionConfig;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.opensymphony.xwork2.util.ValueStack;

/**
 * Generate a page structure according to action information
 * 
 * @author Jerry.Feng Date: 2008-5-15
 */
public class PageStructureInterceptor extends AbstractInterceptor {
	@Resource
	private AutoPageConverterManager pageConverter;
	
	public String intercept(ActionInvocation invocation) throws Exception {
    	ActionConfig config = invocation.getProxy().getConfig();
    	String[] templates = (String[]) invocation.getInvocationContext().getParameters().get(FrameConstant.PARAM_TEMPLATE);
    	String template = null;
    	if (templates != null && templates.length > 0) {
    		template = templates[0];
    	}
    	PageElements elements = pageConverter
				.convertActionClass(invocation.getAction().getClass(), template);
    	ValueStack stack = invocation.getStack();
    	Map<String, Object> context = stack.getContext();
    	context.put(FrameConstant.STACK_PAGEELEMENTS, elements);
    	
    	return invocation.invoke();
	}
}